package com.briup.estore.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.briup.estore.bean.Customer;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = "/login/*")
public class LoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public LoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String url = req.getHeader("Referer");

		if (url != null) {
			String path = url.substring(url.indexOf("EStore/") + 6);
			req.getSession().setAttribute("path", path);
		}

		Customer customer = (Customer) req.getSession().getAttribute("customer");

		if (customer == null) {
			req.getRequestDispatcher("/login").forward(request, response);
			return;
		}

		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	public static void main(String[] args) {
		String path = "/login/shopCart";
		if (path.matches("^/login/[a-zA-Z1-9_/]+")) {
			System.out.println("path>>保存到session");
		}
	}

}
